import { defineStore } from 'pinia'
import type { LoginRequest, LoginResponse } from '../utils/simpleApi'
import { loginApi, logout, checkAuth } from '../utils/simpleApi'
import { rsaUtils } from '../utils/rsa'
import { encryptPassword } from '../utils/crypto'

// 用户信息接口
export interface User {
  id: string
  account: string
  role_id: number[]
  status: number
}

// 认证状态接口
export interface AuthState {
  user: User | null
  isAuthenticated: boolean
  loading: boolean
  error: string | null
  publicKey: string
  csrfToken: string
}

// 导出 store 类型
export type AuthStore = ReturnType<typeof useAuthStore>

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: null,
    isAuthenticated: false,
    loading: false,
    error: null,
    publicKey: '',
    csrfToken: ''
  }),

  getters: {
    // 获取用户ID
    userId: (state) => state.user?.id || '',
    
    // 获取用户账号
    userAccount: (state) => state.user?.account || '',
    
    // 获取用户角色ID列表
    userRoles: (state) => state.user?.role_id || [],
    
    // 检查用户是否有特定角色
    hasRole: (state) => (roleId: number) => {
      return state.user?.role_id?.includes(roleId) || false
    },
    
    // 检查用户是否已登录
    isLoggedIn: (state) => state.isAuthenticated && state.user !== null
  },

  actions: {
    // 设置加载状态
    setLoading(loading: boolean) {
      this.loading = loading
    },

    // 设置错误信息
    setError(error: string | null) {
      this.error = error
    },

    // 设置用户信息
    setUser(user: User | null) {
      this.user = user
      this.isAuthenticated = user !== null
    },

    // 设置公钥
    setPublicKey(publicKey: string) {
      this.publicKey = publicKey
      rsaUtils.setPublicKey(publicKey)
    },

    // 设置 CSRF Token
    setCsrfToken(token: string) {
      this.csrfToken = token
    },

    // 登录
    async login(loginData: LoginRequest) {
      this.setLoading(true)
      this.setError(null)

      try {
        console.log("Auth Store - 开始登录流程");
        console.log("Auth Store - 传入的loginData.csrf_token:", loginData.csrf_token);
        console.log("Auth Store - store中的csrfToken:", this.csrfToken);
        
        // login.vue 中已经对密码进行了加密，直接使用
        const encryptedPassword = loginData.pwd;
        
        // 使用传入的CSRF令牌，如果不存在则使用store中的
        const csrfTokenToUse = loginData.csrf_token || this.csrfToken;
        console.log("Auth Store - 最终使用的CSRF令牌:", csrfTokenToUse);
        
        const requestData: LoginRequest = {
          ...loginData,
          pwd: encryptedPassword,
          csrf_token: csrfTokenToUse
        }

        console.log("Auth Store - 发送登录请求，数据:", { ...requestData, pwd: "***" });
        const response = await loginApi(requestData)
        console.log("Auth Store - 登录响应:", response);

        if (response.code === 0 && response.payload) {
          const user: User = {
            id: response.payload.id,
            account: response.payload.account,
            role_id: response.payload.role_id,
            status: response.payload.status
          }
          
          this.setUser(user)
          
          // 清除错误信息
          this.setError(null)
          
          return {
            success: true,
            next: response.payload.next || '/admin/'
          }
        } else {
          console.error("Auth Store - 登录失败:", response);
          this.setError(response.msg || '登录失败')
          return {
            success: false,
            error: response.msg || '登录失败'
          }
        }
      } catch (error: any) {
        console.error("Auth Store - 登录异常:", error);
        const errorMessage = error.message || '登录失败，请重试'
        this.setError(errorMessage)
        return {
          success: false,
          error: errorMessage
        }
      } finally {
        this.setLoading(false)
      }
    },

    // 退出登录
    async logout() {
      this.setLoading(true)
      this.setError(null)

      try {
        await logout()
        
        // 清除用户信息
        this.setUser(null)
        this.setPublicKey('')
        this.setCsrfToken('')
        
        return { success: true }
      } catch (error: any) {
        const errorMessage = error.message || '退出登录失败'
        this.setError(errorMessage)
        return {
          success: false,
          error: errorMessage
        }
      } finally {
        this.setLoading(false)
      }
    },

    // 检查登录状态
    async checkAuth() {
      this.setLoading(true)
      this.setError(null)

      try {
        const response = await checkAuth()
        
        if (response.code === 0 && response.payload) {
          const user: User = {
            id: response.payload.id,
            account: response.payload.account,
            role_id: response.payload.role_id,
            status: response.payload.status
          }
          
          this.setUser(user)
          return { success: true, user }
        } else {
          this.setUser(null)
          return { success: false }
        }
      } catch (error: any) {
        this.setUser(null)
        return { success: false }
      } finally {
        this.setLoading(false)
      }
    },

    // 初始化认证状态
    async initAuth() {
      // 从 cookie 中获取用户信息
      if (process.client) {
        const cookies = document.cookie.split(';')
        const admUserIdCookie = cookies.find(cookie => cookie.trim().startsWith('adm_user_id='))
        
        if (admUserIdCookie) {
          const userId = admUserIdCookie.split('=')[1]
          if (userId && userId !== '') {
            // 有用户ID，检查认证状态
            return await this.checkAuth()
          }
        }
      }
      
      return { success: false }
    },

    // 清除认证状态
    clearAuth() {
      this.setUser(null)
      this.setPublicKey('')
      this.setCsrfToken('')
      this.setError(null)
      this.setLoading(false)
    }
  }
})